package com.koron.operation.util;

import com.koron.bean.system.org.OrgBean;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jzp
 * @since 2022/7/4
 */
public class SortUtil {

    /**
     * 部门 根据树排序
     */
    public static List<OrgBean> deptSortByTreeLevel(List<OrgBean> source, String rootLevel) {
        // 最终结果，先存顶级节点
        List<OrgBean> result = source.stream().filter(e -> rootLevel.equals(e.getLevel())).collect(Collectors.toList());
        // 从第下一层开始
        int initLevel = Integer.parseInt(rootLevel);
        // 筛选每一层的数据
        while (true) {
            int finalInitLevel = initLevel;
            List<OrgBean> collect = source.stream().filter(e -> String.valueOf(finalInitLevel).equals(e.getLevel())).collect(Collectors.toList());
            if (collect.size() == 0) {
                break;
            }
            for (int i = 0; i < result.size(); i++) {
                OrgBean orgBean = result.get(i);
                // 从result中找父级节点
                if (String.valueOf(initLevel-1).equals(orgBean.getLevel())){
                    List<OrgBean> child = collect.stream().filter(e -> orgBean.getId().equals(e.getParent())).collect(Collectors.toList());
                    result.addAll(i+1, child);
                    i += child.size();
                }
            }
            initLevel += 1;
        }
        return result;
    }

}
